<template>
  <div class="card-header">漏损静态分析</div>
  <div style="flex: 1; width: 100%; overflow: auto; background-color: aliceblue" v-loading="loading">
    <StaticDataAnalysis :meter-list="meterList" />
  </div>
</template>
<script setup>
import { useCompanyStore } from "@/stores/company";
import { useMeterStore } from "@/stores/meter"; // 👈 添加这个
import { ref, watch, provide } from "vue";
import dayjs from "dayjs";
import StaticDataAnalysis from "@/views/WarningCenter/WaterLeakageAnalysis/components/StaticDataAnalysis.vue";
import { getWaterStaticApi } from "@/api/waterLeakage";
import { handleError } from "@/utils/handleError";

// 统一的漏水判断函数
const isLeakedMeter = (meterItem) => {
  if (meterItem.is_drain_considerd === false) {
    return false;
  }
  return +meterItem.value > 0;
};

provide('isLeakedMeter', isLeakedMeter);

const defaultDateRange = [
  dayjs().subtract(3, "day").startOf("day").valueOf(),
  dayjs().subtract(1, "day").endOf("day").valueOf(),
];

const dateRange = ref(defaultDateRange);
let meterList = ref([]);
let loading = ref(false);

// 👇 添加 meterStore
const meterStore = useMeterStore();
const companyStore = useCompanyStore();

// 修改数据获取逻辑
const fetchMeterData = async (startDate, endDate) => {
  loading.value = true;
  try {
    let res = await getWaterStaticApi({
      id: companyStore.currentCompany.id,
      start_time: startDate,
      end_time: endDate,
    });
    if (res.code !== 200) {
      ElMessage.error(res.message || "静态分析统计失败");
      console.error(res);
      return;
    }

    // 👇 合并完整的表计信息
    meterList.value = res.data.map((item) => {
      let meterInfo = meterStore.meterList.find((meter) => meter.id === item.id)
      return {
        ...item,        // 统计数据
        ...meterInfo,   // 完整表计信息（包含 is_drain_considerd）
      }
    });
  } catch (error) {
    handleError(error, "静态分析统计失败");
  } finally {
    loading.value = false;
  }
};

watch(
  () => companyStore.currentCompany,
  async () => {
    // 👇 确保先加载表计列表，再获取统计数据
    if (companyStore.currentCompany.id) {
      await meterStore.fetchMeterList({
        company_id: companyStore.currentCompany.id,
        type: 1,
      });
      await fetchMeterData(dateRange.value[0], dateRange.value[1]);
    }
  },
  {
    immediate: true,
  }
);
</script>